<?php


namespace app\api\controller\shouye;

use app\common\controller\Api;
use think\Db;
use \app\admin\model\activityform\Fromurl as FromurlModel;
use \app\admin\model\activityform\Fromurldata as FromurldataModel;
use \app\admin\model\activityform\Fromurlque as FromurlqueModel;
use Carbon\Carbon;
use app\common\model\User;

class Questionnaire extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 获取问卷列表
     */
    public function infoList()
    {

        $list = FromurlModel::where("status", "normal")
            // ->order("create_time", "desc")
            ->paginate()
            ->each(function ($info, $key) {
                $info->user_num = FromurldataModel::where('fromurl_id', $info->id)
                    ->group('user_id')
                    ->count();
                $ids = explode(',', $info->fromurlques_ids);
                $info->fromurlques_num = count($ids);
            });
        $this->success('获取成功', $list);
    }


    /**
     * 获取问卷状态
     */
    public function infostate($id)
    {

        $info = FromurlModel::where("id", $id)->find();
        $info->user_complete_state = false;
        $user_data = FromurldataModel::where("user_id", $this->auth->id)->where("fromurl_id", $info->id)->find();
        $info->user_complete_state = false;
        if ($user_data) {
            $info->user_complete_state = true;
        }
        $info->user_num = FromurldataModel::where('fromurl_id', $info->id)
            ->group('user_id')
            ->count();
        $ids = explode(',', $info->fromurlques_ids);
        $info->fromurlques_num = count($ids);
        $this->success('获取成功', $info);
    }

    /**
     * 问卷详情
     */
    public function details($id)
    {
        $info = FromurlModel::where("id", $id)->find();
        $ids = explode(',', $info->fromurlques_ids);
        $details = FromurlqueModel::where("id", "in", $ids)->select();
        // $details = FromurlqueModel::where("type", "!=", "text")->select();
        $form = array();
        $rules = array();
        foreach ($details as $key => $value) {

            if ($value->type == "checkbox") {
                $value->result = [];
                $form["result" . $key] = [];
            } else {
                $value->result = '';
                $form["result" . $key] = "";
            }
            $value->association = [];

            if ($value->type == "input") {
                $rules["result" . $key] = [[
                    "required" => true,
                    "message" =>  '必选',
                    "trigger" =>  ['blur', 'change']

                ]];
            }
            if ($value->type == "radio") {
                $rules["result" . $key] = [[
                    "required" => true,
                    "message" =>  '请选择',
                    "trigger" =>  ['blur', 'change']

                ]];
            }

            if ($value->type == "checkbox") {
                $rules["result" . $key] = [[
                    "required" => true,
                    "type" => 'array',
                    "message" =>  '请选择',
                    "trigger" =>  ['blur', 'change']

                ]];
            }

            if ($value->type == "image") {
                $rules["result" . $key] = [[
                    "required" => true,
                    "message" =>  '请上传图片',
                    "trigger" =>  ['blur', 'change']

                ]];
            }

            $value->data = FromurlqueModel::where("pid", $value->id)->select();
        }
        $this->success('获取成功', ["details" => $details, "form" => $form, "rules" => $rules]);
    }
    /**
     * 关联问卷题目
     */
    public function association($id)
    {

        $details = FromurlqueModel::where("pid", $id)->select();
        foreach ($details as $key => $value) {
            if ($value->type == "checkbox") {
                $value->result = [];
            } else {
                $value->result = '';
            }
            $value->data = FromurlqueModel::where("pid", $value->id)->select();
        }
        $this->success('获取成功', $details);
    }

    /**
     * 问卷提交
     */
    public function submit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post("data");
            $form = $this->request->post("form");
            $id = $this->request->post("id");
            // 解码并处理 HTML 实体
            $data = json_decode(html_entity_decode($data), true);  // 设置第二个参数为 true 以返回关联数组
            $form = json_decode(html_entity_decode($form), true);

            // 初始化一个空的数组，用于存储最终数据
            $customdata = [];

            // 遍历数据数组
            foreach ($data as $key => $value) {
                // 初始化单个数据项的结果
                $result = [];

                // 将表单结果添加到 result 数组
                $result[$value["name"]] = $form["result" . $key];
                $customdata[] = $result;

                // 遍历关联项
                foreach ($value["association"] as $ke => $valu) {
                    $association = [];

                    // 处理关联项的数据
                    $association[$valu["name"]] = $form["result" . $key . "-" . $ke];
                    $customdata[] = $association;
                }
            }

            $fromurldata = [
                "fromurl_id" => $id,
                "user_id" => $this->auth->id,
                "customdata" => json_encode($customdata, JSON_UNESCAPED_UNICODE),
                "createtime" => time(),
                "phone" => $this->auth->mobile,
                "name" => $this->auth->nickname,
            ];
            $record = FromurldataModel::insert($fromurldata);
            if ($record) {
                $this->success('提交成功');
            }
            $this->error('提交失败');
        }
        $this->error('非法请求');
    }
}
